import UserMgr from '@/user/user.js'
import * as NetApi from "@/helper/request.js"
import BaseUserInfo from '@/user/baseUserInfo.js';
import {router,RouterMount} from "@/helper/router.js"

export default class WeiXinAuth {
	static shareInstance() {
		if(!this.s_instance) {
			this.s_instance = new WeiXinAuth();
		}
		return this.s_instance;
	}
	
	static destoryInstance() {
		s_instance = null;
	}
	
	isLogined(){
		return this.checkTokenValid();
	}
	
	checkTokenValid() {
	  const token = uni.getStorageSync('token');
	  
	  if (!token) {
		return Promise.resolve(false);
	  }
	
	  return NetApi.postMethod('/loyu-api/app/wechat/checkLogin')
		.then(ok => {
		  this.saveInfo(ok.data, false);
		  return true;
		})
		.catch(error => {
		  return false;
		});
	}
	
	login() {
		return new Promise((resolve, reject) => {
		uni.login({
		  provider: 'weixin',
		  success: (loginRes) => {
			NetApi.postMethod('/loyu-api/app/wechat/login', { wxCode: loginRes.code })
			  .then(ok => {
				const loginResult = ok.data;
				if (loginResult.sysUser) {
					this.saveInfo(loginResult, true)
				  resolve({ success: true, hasUserInfo: true}); // 返回登录结果
				} else {
				  this.openId = loginResult.openId;
				  resolve({ success: true, hasUserInfo: false, openId:loginResult.openId});
				}
			  })
			  .catch(err => {
				console.error("API请求失败", err);
				reject({ success: false, hasUserInfo: false });
			  });
		  },
		  fail: (error) => {
			console.error("微信登录失败", error);
			reject({ success: false, hasUserInfo: false });
		  }
		});
		});
	}
	
	saveInfo(loginResult, updateToken){
		if(loginResult.sysUser) {
			let userMgr = UserMgr.shareInstance();
			let userInfo = new BaseUserInfo({
				nickName:loginResult.sysUser.nickName || '',
				userName:loginResult.sysUser.userName || '',
				phonenumber:loginResult.sysUser.phonenumber || '',
				userId:loginResult.sysUser.userId || '',
				token:loginResult.token || '',
				position:loginResult.sysUser.position || '',
				roles:loginResult.sysUser.roles || [],
				sysUserItems:loginResult.sysUser.sysUserItems || []
			});
			userMgr.updateCurrentUserInfo(userInfo);
			
			if(updateToken) {
				uni.setStorageSync('token', loginResult.token);
			}
		}
	}
	
	isNeedRegister() {
		// #ifdef MP-WEIXIN
	    return this.isLogined()
	        .then(ok => {
	            if (!ok) {
	                return this.login().then(
	                    loginResult => {
	                        if (loginResult.success && !loginResult.hasUserInfo) {
	                            this.openId = loginResult.openId;
	                            return { needRegister: true };
	                        }
	                        return { needRegister: false };
	                    },
	                    () => ({ needRegister: false })
	                );
	            }
	            return { needRegister: false };
	        })
	        .catch(() => ({ needRegister: false }));
		// #endif
		// #ifdef H5
		return Promise.resolve({ needRegister: false });
		// #endif
	}
	
	getRoleNameByItemId(itemId, roles, sysUserItems) {
		    // 定义角色枚举值
		    const roleEnum = [
		        { roleId: 1, roleName: "管理" },
		        { roleId: 2, roleName: "管理" },
		        { roleId: 3, roleName: "管理" },
		        { roleId: 4, roleName: "运营" }
		    ];
			
	    // 1. 检查用户角色中是否存在roleId为1或2的角色
	    const hasAdminOrManager = roles.some(role => [1, 2].includes(role.roleId));
	    
	    if (hasAdminOrManager) {
	        // 直接返回"项目管理人员"（因为roleId=1是超级管理员，roleId=2是项目管理人员）
	        // 根据需求描述，这里统一返回"项目管理人员"，但可能需要更精确的判断
	        // 如果确实需要区分，可以修改为：
	        const adminRole = roleEnum.find(r => r.roleId === 1);
	        const managerRole = roleEnum.find(r => r.roleId === 2);
	        // 这里根据需求描述，当存在1或2时返回"项目管理人员"
	        return "管理";
	    }
	    
	    // 2. 如果没有管理员或项目管理人员角色，则检查sysUserItems
	    const userItem = sysUserItems.find(item => item.itemId === itemId);
	    
	    if (userItem) {
	        // 找到对应的角色ID
	        const roleId = userItem.roleId;
	        // 从枚举中查找对应的角色名称
	        const role = roleEnum.find(r => r.roleId === roleId);
	        return role ? role.roleName : '';
	    }
	    
	    // 3. 如果都不满足，返回null
	    return '';
	}
	
	/**
	 * 检查用户是否有特定权限 [告警通知管理] 
	 * @param {Array} roles - 角色数组
	 * @param {Array} sysUserItems - 用户项目关联数组
	 * @returns {boolean} - 是否有权限
	 */
	 checkUserPermission(roles, sysUserItems) {
	    // 检查roles中是否包含项目管理人员(roleId=2)或超级管理员(roleId=1)
	    const hasManagerOrAdmin = roles.some(role => 
	        role.roleName === '项目管理人员' || role.roleName === '超级管理员'
	    );	  
	    
	    // 检查sysUserItems中是否有roleId为1、2或3的项
	    const hasSpecialRoleInItems = sysUserItems.some(item => 
	        [1, 2, 3].includes(item.roleId)
	    );
	    
	    // 满足任一条件即返回true
	    return hasManagerOrAdmin || hasSpecialRoleInItems;
	}
	
	
	canControl(itemId){
		let userMgr = UserMgr.shareInstance();
		let name = this.getRoleNameByItemId(itemId, userMgr.currentUserInfo.roles || [], userMgr.currentUserInfo.sysUserItems || [])
		return name == '管理' ? true : false;
		
	}
	canSee(itemId){
		let userMgr = UserMgr.shareInstance();
		let name = this.getRoleNameByItemId(itemId, userMgr.currentUserInfo.roles || [], userMgr.currentUserInfo.sysUserItems || [])
		return name == '运营' ? true : false;
	}
	canDoNothing(itemId){
		let userMgr = UserMgr.shareInstance();
		let name = this.getRoleNameByItemId(itemId, userMgr.currentUserInfo.roles || [], userMgr.currentUserInfo.sysUserItems || [])
		return name == '' ? true : false;
	}
	canAlarmSetting(){
		let userMgr = UserMgr.shareInstance();
		return this.checkUserPermission(userMgr.currentUserInfo.roles || [],userMgr.currentUserInfo.sysUserItems || [])
	}
	
	

}



			
